package com.elong.android.specialhouse.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.adapter.common.BaseViewHolder;
import com.elong.android.specialhouse.adapter.common.PowerAdapter;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.entity.ApartmentDatepickerParam;
import com.elong.android.specialhouse.entity.BookRequestParam;
import com.elong.android.specialhouse.entity.HouseFacility;
import com.elong.android.specialhouse.entity.HouseImageItem;
import com.elong.android.specialhouse.entity.HouseInfo;
import com.elong.android.specialhouse.entity.HouseInfoRequestParam;
import com.elong.android.specialhouse.entity.HouseItemList;
import com.elong.android.specialhouse.entity.Landloard;
import com.elong.android.specialhouse.entity.response.Commentltem;
import com.elong.android.specialhouse.request.CollectionReq;
import com.elong.android.specialhouse.request.GetApartmentDetailsRep;
import com.elong.android.specialhouse.ui.CircleImageView;
import com.elong.android.specialhouse.ui.HorizontalListView;
import com.elong.android.specialhouse.ui.LimitedListView;
import com.elong.android.specialhouse.ui.observeablescrollview.ObservableScrollView;
import com.elong.android.specialhouse.ui.observeablescrollview.ObservableScrollViewCallbacks;
import com.elong.android.specialhouse.ui.observeablescrollview.ScrollState;
import com.elong.android.specialhouse.utils.CalendarUtils;
import com.elong.android.specialhouse.utils.DateTimeUtils;
import com.elong.android.specialhouse.utils.EventReportTools;
import com.elong.android.specialhouse.utils.FileUtils;
import com.elong.android.specialhouse.utils.GetFacilitiesIcon;
import com.elong.android.specialhouse.utils.ImageLoaderUtils;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;
import com.elong.myelong.activity.LoginActivity;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author kaiqi.li
 * @ClassName: ApartmentDetailsActivity
 * @Description: 公寓详情页
 * @date 2015-7-30 下午6:29:37
 */
@SuppressLint("NewApi")
public class ApartmentDetailsActivity extends BaseVolleyActivity<IResponse<?>> implements OnClickListener ,ObservableScrollViewCallbacks,AdapterView.OnItemClickListener{
    private static final String PAGE_NAME = "youfangDetailPage";
    private static final String TAG = ApartmentDetailsActivity.class.getSimpleName() ;
    public static final String KEY_IS_MODIFY_COLLECTION = "isModifyCollection";
    private static final String POINT = " 分";
    private static final String NUM = " 条";
    private static final String DATE_FORMAT_PATTERN = "MM月dd日";
    private static final String CHECK_DATE_FORMAT_PATTERN = "yyyy-MM-dd";
    private static final int DEFAULT_LIVE_NIGHT = 5;

    private static final int COMMENT_TITLE_TEXT_SIZE = 20; // 评论标题数字字体Size 20sp
    private static final int REQUEST_CODE_DATE_PICKER = 100;
    private String[] dayInWeekTexts;
    private int mapImgWidth;
    private int mapImgHeight;
    private String mapImgUrl;

    private ImageLoader imageLoader ;
    private DisplayImageOptions options;

    /**
     * ***************
     * View
     * ***********************
     */
    private TextView rlHeader ;
    private ObservableScrollView mScrollView ;
    private HorizontalListView mOtherApartment;
    private PowerAdapter<HouseItemList> mOtherApartmentAdapter;
    private List<HouseItemList> mOtherApartmentDatas;

    private TextView mCallLandlordTv;
    private TextView mCheckInDateTv;
    private TextView mCheckOutDateTv;
    private TextView mTotalNightTv;
    private TextView mPriceOneNightTv;
    private TextView mCommentScoreTv;
    private TextView mCommentNumTv;
    private ImageView mMapImage;
    private CircleImageView mLandlordPhoto;
    private TextView mLandlordName;
    private ImageView mHouseCoverPic;
    private TextView mHouseDesc;
    private TextView mAddressText;
    private TextView mHouseType; //房源类型TextView
    private TextView mRoomAndLobby;//几室几厅TextView
    private TextView mNumOfBeds;//床位数TextView
    private LimitedListView mLlvCommentContent;//评论内容
    private LimitedListView mLlvBookingRules;//约定规则
    private LimitedListView mLlvCancelRules;//取消规则
    private LimitedListView mLlvDiscountInfo;//优惠信息
    private LimitedListView mLlvBasicFacilities ;//基础设施
    private TextView tvAveragePrice ;


    private Button mMoreCommentsBtn;
    private Button mMoreFacilitiesBtn;
    private Button btnBookNow;

    /**
     * Title
     */
    private ImageView mBackImg;
    private ImageView mCollectImg;
    private TextView mTitleTv;

    /**
     * ********************
     * DATA
     * ************************
     */
    private HouseInfo houseInfo;       //房源基本信息
    private int commentCount;         //评论数
    private String commentScore;     //评分
    private List<Commentltem> commentltems;       //评论内容列表
    private Landloard landloardInfo; //房东信息
    private String dailyPrice;       //出租价格
    private boolean isCollected;    //是否已收藏
    private double totalHousePrice ;   //总房费
    private double totalServicePrice ; //总服务费
    private boolean isBookable ;        //是否可预订
    private long totalDays ;         //总入住天数
    private int maxPeopleNum ;      //最大可入住人数

    private HouseInfoRequestParam preloadingData; //列表页带过来的数据
    private Calendar checkInDate ;
    private Calendar checkOutDate ;
    private HouseItemList houseBasicInfo;
    private long houseId ;

    private int longestStay  = 365 ;   //最长入住
    private int shortestStay = 1 ;  //最短入住
    private int checkInEarly = 0 ;  //最长入住
    private boolean isModifyCollection = false ;
    private String[] bedTypeList ;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventReportTools.sendPageOpenEvent(PAGE_NAME);
    }
    @Override
    protected void initContentView() {
        setContentView(R.layout.act_apartment_details);
        bedTypeList = getResources().getStringArray(R.array.house_bed_type_list);
        preloadingData = (HouseInfoRequestParam) getIntent().getSerializableExtra("ApartmentInfoRequestParam");
        if (preloadingData != null) {
            houseBasicInfo = preloadingData.HouseItemList;
            houseId = houseBasicInfo.HouseId;
        } else {
            houseId = getIntent().getLongExtra(AppConstants.APARTMENT_ID,0);
        }
        initView();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mapImgWidth = (int) (dm.widthPixels * dm.density);
        mapImgHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());
        options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.bg_loading_default)
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED).build();
        imageLoader = ImageLoader.getInstance() ;
        dayInWeekTexts = getResources().getStringArray(R.array.calendar_text);

//        preloadingData();
        if (preloadingData != null) {
            setUpCheckInAndOutDate(preloadingData.CheckInDate, preloadingData.CheckOutDate);
        } else {
            Calendar in = CalendarUtils.getCalendarInstance();
            Calendar out = CalendarUtils.getCalendarInstance();
            out.add(Calendar.DAY_OF_MONTH, AppConstants.DEFAULT_CHECKIN_CHECKOUT_DAYS);
            setUpCheckInAndOutDate(in,out) ;
        }

        requestApartmentDetails(houseId +"",checkInDate, checkOutDate);
    }

    private void initView() {

        mScrollView = (ObservableScrollView) findViewById(R.id.observable_scrollview) ;
        mScrollView.setScrollViewCallbacks(this);
        rlHeader = (TextView) findViewById(R.id.tv_header);
        ViewPropertyAnimator.animate(rlHeader).setDuration(100).alpha(0.5f).start();

        mBackImg = (ImageView) findViewById(R.id.details_head_back);
        mBackImg.setOnClickListener(this);
        mCollectImg = (ImageView) findViewById(R.id.details_head_like);
        mCollectImg.setOnClickListener(this);
        mTitleTv = (TextView) findViewById(R.id.details_head_title);

        mCallLandlordTv = (TextView) findViewById(R.id.tv_detail_call_landlord);
        mCallLandlordTv.setOnClickListener(this);
        mCheckInDateTv = (TextView) findViewById(R.id.tv_details_check_in_date);
        mCheckInDateTv.setOnClickListener(this);
        mCheckOutDateTv = (TextView) findViewById(R.id.tv_details_departure_date);
        mCheckOutDateTv.setOnClickListener(this);
        mTotalNightTv = (TextView) findViewById(R.id.tv_details_total_days);
        mTotalNightTv.setOnClickListener(this);
        mPriceOneNightTv = (TextView) findViewById(R.id.tv_details_price);
        mCommentScoreTv = (TextView) findViewById(R.id.tv_details_comment_score);
        mCommentNumTv = (TextView) findViewById(R.id.tv_details_comment_num);
        mMoreCommentsBtn = (Button) findViewById(R.id.btn_details_more_comments);
        mMoreCommentsBtn.setOnClickListener(this);
        mMoreFacilitiesBtn = (Button) findViewById(R.id.btn_details_more_facilities);
        mMoreFacilitiesBtn.setOnClickListener(this);
        btnBookNow = (Button) findViewById(R.id.btn_book);
        btnBookNow.setOnClickListener(this);
        mMapImage = (ImageView) findViewById(R.id.img_details_map);
        mMapImage.setOnClickListener(this);
        mLandlordPhoto = (CircleImageView) findViewById(R.id.cimg_detail_landlord_photo);
        mLandlordPhoto.setOnClickListener(this);
        mLandlordName = (TextView) findViewById(R.id.tv_detail_landlord_name);
        mHouseCoverPic = (ImageView) findViewById(R.id.iv_photo);
        mHouseCoverPic.setOnClickListener(this);
        mHouseDesc = (TextView) findViewById(R.id.tv_detail_room_desc);
        mAddressText = (TextView) findViewById(R.id.tv_details_address);
        mAddressText.setOnLongClickListener(new View.OnLongClickListener() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @Override
            public boolean onLongClick(View v) {
                ClipboardManager clip = (ClipboardManager) ApartmentDetailsActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
                clip.setPrimaryClip(ClipData.newPlainText("address name", mAddressText.getText()));
                Toast.makeText(ApartmentDetailsActivity.this,"已成功复制到剪贴板", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        mHouseType = (TextView) findViewById(R.id.tv_detail_room_type);
        mRoomAndLobby = (TextView) findViewById(R.id.tv_detail_room_num);
        mNumOfBeds = (TextView) findViewById(R.id.tv_detail_bed_num);
        mLlvCommentContent = (LimitedListView) findViewById(R.id.llv_details_comment_content);
        mLlvBookingRules = (LimitedListView) findViewById(R.id.tv_details_predestine_rules_content);
        mLlvCancelRules = (LimitedListView) findViewById(R.id.tv_details_cancel_rules_content);
        mLlvDiscountInfo = (LimitedListView) findViewById(R.id.llv_details_discount_tip);
        mLlvBasicFacilities = (LimitedListView) findViewById(R.id.apartment_detail_basic_facilities);
        mOtherApartment = (HorizontalListView) findViewById(R.id.details_other_apartments);
        tvAveragePrice = (TextView) findViewById(R.id.tv_details_avg_price);
    }

    /**
     * 网络请求 详情数据
     */
    private void requestApartmentDetails(String houseId ,Calendar checkInDate,Calendar checkOutDate) {
        GetApartmentDetailsRep req = new GetApartmentDetailsRep();
        req.houseId = houseId + "";
        req.checkInDate = DateTimeUtils.formatDateByPattern(checkInDate, CHECK_DATE_FORMAT_PATTERN);
        req.checkOutDate = DateTimeUtils.formatDateByPattern(checkOutDate, CHECK_DATE_FORMAT_PATTERN);
        if (Account.getInstance().isLogin()) {
            req.userId = Account.getInstance().getUserId();
        }
        requestHttp(req, ApartmentAPI.getApartmentDetails, StringResponse.class,true);
    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        String content = ((StringResponse) t).getContent();
        JSONObject result = JSONObject.parseObject(content);
        boolean isHandlerError = handleIsError(request, result);
        if (!isHandlerError) {
            switch ((ApartmentAPI) request.getRequestOption().getHusky()) {
                case getApartmentDetails:
                    totalHousePrice = Double.parseDouble(result.getString(JSONConstants.ATTR_TOTAL_HOUSE_PRICE));
                    totalServicePrice = Double.parseDouble(result.getString(JSONConstants.ATTR_TOTAL_SERVICE_PRICE));
                    isBookable = result.getBooleanValue(JSONConstants.ATTR_IS_BOOKABLE);
                    //房源基本信息
                    mTitleTv.setText(result.getString(JSONConstants.ATTR_HOUSE_NAME) + "");
                    houseInfo = JSONObject.parseObject(result.getString(JSONConstants.ATTR_HOUSE_INFO), HouseInfo.class);
                    if (houseInfo == null) {
                        Toast.makeText(this, "获取详情失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    btnBookNow.setEnabled(isBookable);
                    //是否已收藏
                    isCollected = result.getBooleanValue(JSONConstants.ATTR_IS_COLLECTED);
                    mCollectImg.setImageResource(isCollected ? R.drawable.icon_collect_selected : R.drawable.icon_collect_unselected);
                    //出租价格
                    dailyPrice = result.getString(JSONConstants.ATTR_DAILY_PRICE);
                    setupDailyPrice(dailyPrice);
                    //评论信息
                    JSONObject comment = JSONObject.parseObject(result.getString(JSONConstants.ATTR_COMMENT));
                    commentCount = comment.getIntValue(JSONConstants.ATTR_COMMENT_COUNT);
                    commentScore = comment.getString(JSONConstants.ATTR_RATING);
                    JSONArray comments = comment.getJSONArray(JSONConstants.ATTR_COMMENT_ITEMS);
                    commentltems = JSONArray.parseArray(JSONArray.toJSONString(comments), Commentltem.class);

                    //房东信息
                    landloardInfo = JSONObject.parseObject(result.getString(JSONConstants.ATTR_LANDLOARD), Landloard.class);
                    //其它房源信息
                    mOtherApartmentDatas = JSONArray.parseArray(JSONArray.toJSONString(result.getJSONArray(JSONConstants.ATTR_OTHER_HOUSE)), HouseItemList.class);
                    setupOtherHouse(mOtherApartmentDatas);

                    setupComment(commentScore, commentCount);
                    setupLandlordInfo(landloardInfo);
                    setupHouseBasicInfo(houseInfo);
                    setupBasicFacilities();
                    break;
                case addCollectionInfo:
                    isModifyCollection = true ;
                    Toast.makeText(this, R.string.add_collection_success,Toast.LENGTH_SHORT).show();
                    isCollected = true;
                    mCollectImg.setImageResource( R.drawable.icon_collect_selected);
                    break;
                case deleteCollectionInfo:
                    isModifyCollection = true ;
                    Toast.makeText(this, R.string.cancel_collection_success,Toast.LENGTH_SHORT).show();
                    isCollected = false;
                    mCollectImg.setImageResource(R.drawable.icon_collect_unselected);
                    break;
                default:
                    break;
            }
        } else {
            switch ((ApartmentAPI) request.getRequestOption().getHusky()) {
                case addCollectionInfo:
                    mCollectImg.setImageResource(isCollected ? R.drawable.icon_collect_selected : R.drawable.icon_collect_unselected);
                    Toast.makeText(this,"添加收藏失败",Toast.LENGTH_SHORT).show();
                    break;
                case deleteCollectionInfo:
                    mCollectImg.setImageResource(isCollected ? R.drawable.icon_collect_selected : R.drawable.icon_collect_unselected);
                    Toast.makeText(this,"取消收藏失败",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    }

    private void setupAddress(String Longitude, String Latitude) {
        mapImgUrl = "http://api.map.baidu.com/staticimage?width=" +
                (mapImgWidth > 1024 ? 1024 : mapImgWidth) + "&height=" + mapImgHeight + "" +
                "&center=" + Longitude + "," + Latitude + "&zoom=15&dpiType=ph";
        imageLoader.displayImage(mapImgUrl, mMapImage, options);
    }

    /**
     * 设置房源基本信息
     *
     * @param house
     */
    private void setupHouseBasicInfo(HouseInfo house) {
        String imgPath = house.CoverPicUrl ;
        if (TextUtils.isEmpty(house.CoverPicUrl)) {
            if (house.HouseImages != null && house.HouseImages.size() > 0) {
                imgPath = house.HouseImages.get(0).ImagePath ;
            }
        }
        imageLoader.displayImage(imgPath, mHouseCoverPic, options);

        //设置图片数量
        if (house.HouseImages != null && house.HouseImages.size() > 0){
            ((TextView) findViewById(R.id.tv_details_image_num)).setText("共"+house.HouseImages.size()+"张");
        }

        if (!TextUtils.isEmpty(house.HouseDesc)) {
            StringBuilder houseDesc = new StringBuilder("\t\t");
            houseDesc.append("\"");
            houseDesc.append(house.HouseDesc);
            houseDesc.append("\"");
            mHouseDesc.setText(houseDesc.toString());
        }
        //设置位置信息
        String address = TextUtils.isEmpty(house.Address) ? "" : house.Address;
        //去除分隔符
        address = address.replace(AppConstants.HOUSE_LOCATION_SPLIT, "");
        mAddressText.setText(address);
        setupAddress(house.BaiduLongitude, house.BaiduLatitude);
        // 设置约定/取消规则
        setupRules(house.BookingRules, house.CancelRules);
        //设置优惠信息
        setupDiscountInfos(house.DiscountInfos);
        //设置房源户型、类型信息
        mHouseType.setText(FileUtils.retrieveApartmentTypeById(this, house.HouseType));
//        mNumOfBeds.setText((Integer.parseInt(house.NumOfBeds) > 15 ? "15+" : house.NumOfBeds) + "张床");
        int numOfBed = Integer.parseInt(house.NumOfBeds);
        if (numOfBed > 15) {
            mNumOfBeds.setText("15+张床");
        }else if (numOfBed < 1) {
            mNumOfBeds.setText("1张床");
        } else {
            mNumOfBeds.setText(numOfBed + "张床");
        }

        switch (house.RentalType) {
            case AppConstants.SPACE_TYPE_WHOLE_HOUSE:    //整租
                mRoomAndLobby.setText(house.RoomAndLobby + "");
                break;
            case AppConstants.SPACE_TYPE_ONE_ROOM:    //单间
                mRoomAndLobby.setText(R.string.house_type_room);
                break;
            case AppConstants.SPACE_TYPE_BED_ONLY:    //床位
                mRoomAndLobby.setText(R.string.house_type_bed);
                mNumOfBeds.setText(bedTypeList[house.BedType]);
                break;
            default:
                break;
        }
    }

    /**
     * 设置预定取消规则
     *
     * @param bookRules
     * @param cancelRules
     */
    private void setupRules(List<String> bookRules, List<String> cancelRules) {
        //设置预定规则的int值，最为日历筛选的入参
        getBookRulesIntValus(bookRules);
        PowerAdapter<String> bookAdapter = new PowerAdapter<String>(this, R.layout.item_details_rules, bookRules) {
            @Override
            protected void convert(BaseViewHolder holder, String item) {
                holder.setText(R.id.tv_rules_text, (holder.getPosition() + 1) +"."+item);
            }
        };
        mLlvBookingRules.setAdapter(bookAdapter);
        PowerAdapter<String> cancelAdapter = new PowerAdapter<String>(this, R.layout.item_details_rules, cancelRules) {
            @Override
            protected void convert(BaseViewHolder holder, String item) {
                holder.setText(R.id.tv_rules_text, (holder.getPosition() + 1) +"."+item);
            }
        };
        mLlvCancelRules.setAdapter(cancelAdapter);
    }

    /**
     * 设置优惠信息
     *
     * @param discountInfos
     */
    private void setupDiscountInfos(List<String> discountInfos) {
        //设置每天均价
//        int averagePrice = (int)(totalHousePrice / totalDays) ;
        int dailyPrice = StringUtils.format(this.dailyPrice);

        int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, COMMENT_TITLE_TEXT_SIZE, getResources().getDisplayMetrics());
        SpannableString span = new SpannableString("平均每晚￥" + dailyPrice + "/晚");
        span.setSpan(new AbsoluteSizeSpan(size, false), 5, span.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.theme_red)), 5, span.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvAveragePrice.setText(span);

        PowerAdapter<String> discountAdapter = new PowerAdapter<String>(this, R.layout.item_details_discount, discountInfos) {
            @Override
            protected void convert(BaseViewHolder holder, String item) {
                holder.setText(R.id.tv_rules_text, item);
            }
        };
        mLlvDiscountInfo.setAdapter(discountAdapter);
    }

    /**
     * 设置基础设施显示
     */
    private void setupBasicFacilities() {
        List<HouseFacility> facilities = new ArrayList<HouseFacility>();
        if (houseInfo.RoomFacilities != null && houseInfo.RoomFacilities.size() > 0) {
            facilities.addAll(houseInfo.RoomFacilities);
        }
        if (houseInfo.CommunalFacilities!= null && houseInfo.CommunalFacilities.size() > 0) {
            facilities.addAll(houseInfo.CommunalFacilities);
        }
        if (houseInfo.SpecialFacilities!= null && houseInfo.SpecialFacilities.size() > 0) {
            facilities.addAll(houseInfo.SpecialFacilities);
        }
        if (facilities != null && facilities.size() > 8) {
            facilities = facilities.subList(0, 8);
        }
        PowerAdapter<HouseFacility> mFacilitiesAdapter = new PowerAdapter<HouseFacility>(this, R.layout.item_facilities, facilities) {
            @Override
            protected void convert(BaseViewHolder holder, HouseFacility item) {
                Bitmap icon = GetFacilitiesIcon.getInstance(ApartmentDetailsActivity.this).getImage(item.FacilityID);
                holder.setImageBitmap(R.id.iv_facility, icon);
            }
        };
        mLlvBasicFacilities.setAdapter(mFacilitiesAdapter);
        if (facilities.size() > 0) {
            mMoreFacilitiesBtn.setVisibility(View.VISIBLE);
        } else {
            mMoreFacilitiesBtn.setVisibility(View.GONE);
        }
    }

    /**
     * 设置其它房源
     * @param mOtherApartmentDatas
     */
    private void setupOtherHouse(List<HouseItemList> mOtherApartmentDatas) {
        if (mOtherApartmentDatas != null && mOtherApartmentDatas.size() > 0) {
            findViewById(R.id.rl_details_other_apartments).setVisibility(View.VISIBLE);
            mOtherApartmentAdapter = new PowerAdapter<HouseItemList>(this, R.layout.item_other_apartment, mOtherApartmentDatas) {
                @Override
                protected void convert(BaseViewHolder holder, HouseItemList item) {
                    holder.setImageUrl(R.id.iv_other_house_pic, item.RoomPicUrl);
                    holder.setText(R.id.tv_room_price, getOtherHousePrice(item.DailyPrice));
                    int rentalType = item.RentalType ;
                    switch (rentalType) {
                        case AppConstants.SPACE_TYPE_WHOLE_HOUSE:    //整租
                            holder.setText(R.id.tv_room_type, TextUtils.isEmpty(item.RoomAndLobby) ? "" : item.RoomAndLobby);
                            break;
                        case AppConstants.SPACE_TYPE_ONE_ROOM:    //单间
                            holder.setText(R.id.tv_room_type, R.string.house_type_room);
                            break;
                        case AppConstants.SPACE_TYPE_BED_ONLY:    //床位
                            holder.setText(R.id.tv_room_type, R.string.house_type_bed);
                            break;
                        default:
                            break;
                    }
                }
            };
            mOtherApartment.setAdapter(mOtherApartmentAdapter);
            mOtherApartment.setOnItemClickListener(this);
        } else {
            findViewById(R.id.rl_details_other_apartments).setVisibility(View.GONE);
        }
    }

    /**
     * 设置房东信息
     *
     * @param landloard
     */
    private void setupLandlordInfo(Landloard landloard) {

        mLandlordName.setText(landloard.LandlordName);
        imageLoader.displayImage(landloard.LandlordPicUrl, mLandlordPhoto, ImageLoaderUtils.getHeaderImageOptions());
    }

    /**
     * 设置入离店日期
     *
     * @param checkInCalendar  入店日期
     * @param checkOutCalendar 离店日期
     */
    private void setUpCheckInAndOutDate(Calendar checkInCalendar, Calendar checkOutCalendar) {
        this.checkInDate = checkInCalendar ;
        this.checkOutDate = checkOutCalendar ;
        totalDays = DateTimeUtils.getIntervalTimes(checkInCalendar, checkOutCalendar) ;
        mTotalNightTv.setText("(共" +  totalDays + "晚)");

        String checkInDate = DateTimeUtils.formatDateByPattern(checkInCalendar, DATE_FORMAT_PATTERN);
        String checkOutDate = DateTimeUtils.formatDateByPattern(checkOutCalendar, DATE_FORMAT_PATTERN);
        final String TEXT_CHECK_IN = this.getString(R.string.check_in);
        final String TEXT_CHECK_OUT = this.getString(R.string.check_out);
        int subTextSize = ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14, this.getResources().getDisplayMetrics()));
        SpannableString mCheckInSpann = new SpannableString(TEXT_CHECK_IN + "\n" + checkInDate + "(" + dayInWeekTexts[checkInCalendar.get(Calendar.DAY_OF_WEEK) - 1] + ")");
        mCheckInSpann.setSpan(new AbsoluteSizeSpan(subTextSize, false), TEXT_CHECK_IN.length(), mCheckInSpann.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        SpannableString mCheckOutSpann = new SpannableString(TEXT_CHECK_OUT + "\n" + checkOutDate + "(" + dayInWeekTexts[checkOutCalendar.get(Calendar.DAY_OF_WEEK) - 1] + ")");
        mCheckOutSpann.setSpan(new AbsoluteSizeSpan(subTextSize, false), TEXT_CHECK_IN.length(), mCheckOutSpann.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        mCheckInDateTv.setText(mCheckInSpann);
        mCheckOutDateTv.setText(mCheckOutSpann);
    }

    /**
     * 设置价格标签
     */
    private void setupDailyPrice(String price) {

        SpannableString priceSpan = new SpannableString("￥" + StringUtils.format(price)+ "/晚");
        int priceTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 24, this.getResources().getDisplayMetrics());
        priceSpan.setSpan(new AbsoluteSizeSpan(priceTextSize, false), 1, priceSpan.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        priceSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.theme_yellow)), 1, priceSpan.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mPriceOneNightTv.setText(priceSpan);
    }

    private SpannableString getOtherHousePrice(double price) {
        SpannableString priceSpan = new SpannableString("￥" + StringUtils.format(price) + "/晚");
        int priceTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 18, this.getResources().getDisplayMetrics());
        priceSpan.setSpan(new AbsoluteSizeSpan(priceTextSize, false), 1, priceSpan.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        priceSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.orange)), 1, priceSpan.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return priceSpan ;
    }

    /**
     * 设置评论内容
     *
     * @param score
     * @param totalNum
     */
    private void setupComment(String score, int totalNum) {
        if (totalNum < 1) {
            findViewById(R.id.tv_no_comment_tip).setVisibility(View.VISIBLE);
            mMoreCommentsBtn.setVisibility(View.GONE);
            findViewById(R.id.v_comment_separator).setVisibility(View.GONE);
        } else {
            findViewById(R.id.tv_no_comment_tip).setVisibility(View.GONE);
            mMoreCommentsBtn.setVisibility(View.VISIBLE);
            findViewById(R.id.v_comment_separator).setVisibility(View.VISIBLE);
            score = TextUtils.isEmpty(score) ? "0" : score;
            int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, COMMENT_TITLE_TEXT_SIZE, getResources().getDisplayMetrics());
            SpannableString scoreSpan = new SpannableString(score + POINT);
            scoreSpan.setSpan(new AbsoluteSizeSpan(size, false), 0, scoreSpan.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            scoreSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.theme_red)), 0, scoreSpan.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            SpannableString numSpan = new SpannableString(totalNum + NUM);
            numSpan.setSpan(new AbsoluteSizeSpan(size, false), 0, numSpan.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            numSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.theme_red)), 0, numSpan.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            mCommentScoreTv.setText(scoreSpan);
            mCommentNumTv.setText(numSpan);
            //评论内容
            setupCommentConetent(commentltems);
        }
    }

    /**
     * 详情页设置评论内容 至多显示两条
     *
     * @param comments 评论列表
     */
    private void setupCommentConetent(List<Commentltem> comments) {
        if (comments != null && comments.size() > 0) {
            mMoreCommentsBtn.setVisibility(View.VISIBLE);
        }
        PowerAdapter<Commentltem> adapter = new PowerAdapter<Commentltem>(this, R.layout.item_details_comment, comments) {
            @Override
            protected void convert(BaseViewHolder holder, Commentltem item) {

                StringBuilder builder = new StringBuilder("\"");
                builder.append(item.content);
                builder.append("\"");
                holder.setText(R.id.tv_comment_content_text, builder.toString());
            }
        };
        mLlvCommentContent.setAdapter(adapter);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_DATE_PICKER) {
                Bundle bundle = data.getExtras();
                ApartmentDatepickerParam param = (ApartmentDatepickerParam) bundle.get(ApartmentDatepickerParam.TAG);
                setUpCheckInAndOutDate(param.checkInDate, param.checkOutDate);
                requestApartmentDetails(houseId+"",param.checkInDate,param.checkOutDate);
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.details_head_back:
                onClickBack();
                break;
            case R.id.details_head_like:
                //TODO 提交收藏/取消收藏网络请求
                if (Account.getInstance().isLogin()) {
                    CollectionReq req = new CollectionReq() ;
                    req.HouseId =houseId ;
                    req.UserId = Account.getInstance().getUserId() ;
                    if (isCollected) {
                        requestHttp(req, ApartmentAPI.deleteCollectionInfo,StringResponse.class) ;
                    } else {
                        requestHttp(req, ApartmentAPI.addCollectionInfo,StringResponse.class) ;
                    }
                } else {
                    goToLoginPage();
                }
                break;
            case R.id.iv_photo:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "picture");//图片picture
                gotoDetailImageBrowseActivity();
                break;
            case R.id.cimg_detail_landlord_photo:
                gotoHomePage();
                break;
            case R.id.btn_details_more_comments:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "moreEvaluation");//更多评价moreEvaluation
                gotoMoreComment() ;
                break;
            case R.id.btn_details_more_facilities:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "moreFacilities");//更多设施moreFacilities
                if (houseInfo == null) {
                    return ;
                }
                PopupWindowUtils.popupFacilities(ApartmentDetailsActivity.this, houseInfo.CommunalFacilities, houseInfo.RoomFacilities, houseInfo.SpecialFacilities);
                break;
            case R.id.tv_detail_call_landlord:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "contactLandlord");//联系房东contactLandlord
                gotoChatActivity();
                break;
            case R.id.tv_details_check_in_date:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "arriveLeaveTime ");//入离时间arriveLeaveTime
                gotoDatePicker();
                break;
            case R.id.tv_details_departure_date:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "arriveLeaveTime ");//入离时间arriveLeaveTime
                gotoDatePicker();
                break;
            case R.id.tv_details_total_days:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "arriveLeaveTime ");//入离时间arriveLeaveTime
                gotoDatePicker();
                break;
            case R.id.btn_book:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "immediateBooking ");//立即预定immediateBooking
                if (Account.getInstance().isLogin()) {
                    gotoBook();
                } else {
                    goToLoginPage();
                }
                break;
            case R.id.img_details_map:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "map ");//地图map
                gotoMapActivity();
                break ;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onClickBack();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void onClickBack() {
        EventReportTools.sendPageSpotEvent(PAGE_NAME, "back");//返回back
        if (isModifyCollection) {
            Intent intent = new Intent();
            intent.putExtra(KEY_IS_MODIFY_COLLECTION, isCollected);
            setResult(RESULT_OK, intent);
        }
        back();
    }

    private void gotoHomePage() {
        if(Account.getInstance().isLogin() &&
                landloardInfo.LandlordId.equals(Account.getInstance().getUserId())){
            //房东是自己，查看个人主页 // TODO: 2015/12/16 跳到下载页
//            startActivity(new Intent(this,HomePageMyActivity.class));
        }else{
            //房东是别人，查看房东个人主页
            Intent intent = new Intent(this,HomePageOthersActivity.class);
            intent.putExtra(AppConstants.LANDLORD_ID,landloardInfo.LandlordId);
            intent.putExtra(AppConstants.LANDLORD_NAME,landloardInfo.LandlordName);
            startActivity(intent);
        }
    }
    private void gotoChatActivity() {
        if (!Account.getInstance().isLogin()) {
            Intent intent = new Intent(ApartmentDetailsActivity.this, LoginActivity.class);
            intent.putExtra(AppConstants.ACTIVITY_KEY_FROM_WHERE, TAG);
            startActivity(intent);
            return;
        }
        if (landloardInfo == null) {
            return;
        }
        Intent intent = new Intent(ApartmentDetailsActivity.this, ChatActivity.class);
        intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_ID, Long.parseLong(landloardInfo.LandlordId));
        intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_NAME, landloardInfo.LandlordName);
        startActivity(intent);
    }

	private void gotoMapActivity() {
        if (houseInfo == null) {
            return;
        }
        Intent intent = new Intent(ApartmentDetailsActivity.this, ApartmentMapActivity.class);
        intent.putExtra(AppConstants.ACTIVITY_KEY_HOUSE_BAIDU_LATITUDE, houseInfo.BaiduLatitude);
        intent.putExtra(AppConstants.ACTIVITY_KEY_HOUSE_BAIDU_LONGITUDE, houseInfo.BaiduLongitude);
        intent.putExtra(AppConstants.ACTIVITY_KEY_HOUSE_ADDRESS, houseInfo.Address);
        startActivity(intent);
    }

    private void gotoMoreComment(){
        Intent intent = new Intent(ApartmentDetailsActivity.this, ApartmentCommentActivity.class) ;
        intent.putExtra(AppConstants.ACTIVITY_KEY_HOUSE_ID,houseId) ;
        startActivity(intent);
    }

    private void gotoDatePicker(){
        Intent intent = new Intent(ApartmentDetailsActivity.this, DatePickerActivity.class);
        ApartmentDatepickerParam value = new ApartmentDatepickerParam();
        value.longestStay = longestStay ;
        value.shortestStay = shortestStay ;
        value.checkInEarly = checkInEarly ;
        value.checkInDate = checkInDate;
        value.checkOutDate = checkOutDate;
        value.startDate = DateTimeUtils.getCurrentDateTime();
        value.dateRange = 180;
        value.currentCityType = AppConstants.CITYTYPE_APARTMENT;
        intent.putExtra(ApartmentDatepickerParam.TAG,value);
        intent.putExtra(AppConstants.ACTIVITY_KEY_HOUSE_ID,houseId) ;
        startActivityForResult(intent, REQUEST_CODE_DATE_PICKER);
    }

    private void gotoDetailImageBrowseActivity() {
        if (houseInfo != null && houseInfo.HouseImages != null && houseInfo.HouseImages.size() > 0) {
            List<HouseImageItem> houseImages = houseInfo.HouseImages;
            Intent intent = new Intent(this, ApartmentDetailImageBrowseActivity.class);
            intent.putExtra(AppConstants.ACTIVITY_KEY_HOUSE_IMAGES, (Serializable) houseImages);
            startActivity(intent);
        }
    }

    private void gotoBook() {
        BookRequestParam param = new BookRequestParam() ;
        Intent intent = new Intent(ApartmentDetailsActivity.this, AskForBookingActivity.class);
        param.checkInDate = checkInDate ;
        param.checkOutDate = checkOutDate ;
        param.houseId = houseId ;
        param.isCanCancel = houseInfo.IsCanCancel ;
        param.cancelRulesInner = houseInfo.CancelRulesInner ;
        param.totalRoomPrice = totalHousePrice ;
        param.totalServicePrice = totalServicePrice ;
        param.sumPrice = totalHousePrice + totalServicePrice ;
        param.totalDays = totalDays ;
        param.apartmentName = mTitleTv.getText().toString().trim();
        param.maxPeopleNum = houseInfo != null ? houseInfo.MaxPeopleNum : -1 ;
        intent.putExtra(AppConstants.ACTIVITY_KEY_BOOK_REQUEST_PARAM,param);
        startActivity(intent);
    }
    /**
     * 跳到登录页
     */
    private void goToLoginPage() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra(AppConstants.BUNDLE_KEY_COME_FROM, TAG);
        startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        EventReportTools.sendPageSpotEvent(PAGE_NAME, "otherHouse");//其它房源otherHouse
        Intent intent = new Intent(ApartmentDetailsActivity.this, ApartmentDetailsActivity.class);
        HouseInfoRequestParam param = new HouseInfoRequestParam() ;
        param.HouseItemList = mOtherApartmentAdapter.getItem(position);
        param.CheckInDate = checkInDate ;
        param.CheckOutDate = checkOutDate ;
        intent.putExtra("ApartmentInfoRequestParam", param);
        startActivity(intent);
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        if (mHouseCoverPic.getHeight() <= scrollY) {
            ViewPropertyAnimator.animate(rlHeader).setDuration(100).alpha(1).start();
        } else {
            ViewPropertyAnimator.animate(rlHeader).setDuration(100).alpha(0.5f).start();
        }
    }

    @Override
    public void onDownMotionEvent() {
    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {
        if (scrollState == ScrollState.UP) {
            ViewPropertyAnimator.animate(btnBookNow).setDuration(500).alpha(0).start();
            ViewPropertyAnimator.animate(btnBookNow).setDuration(500).translationY(btnBookNow.getHeight()).start();
        } else if (scrollState == ScrollState.DOWN) {
            ViewPropertyAnimator.animate(btnBookNow).setDuration(500).alpha(1).start();
            ViewPropertyAnimator.animate(btnBookNow).setDuration(500).translationY(0).start();
        }
    }

    /**
     * 提取入住规则中的最长入住天数、最短入住天数、提前入住天数
     * @param param
     * @return
     */
    private String getIntFromString(String param) {
        Pattern p = Pattern.compile("[^0-9]");
        Matcher m = p.matcher(param);
        return m.replaceAll("").trim() ;
    }

    private void getBookRulesIntValus(List<String> rules) {
        List<String> result = new ArrayList<String>();
        int len = rules.size() ;
        for (int i = 0; i < len; i++) {
            if (i == 2) {
                continue;
            }
            result.add(getIntFromString(rules.get(i)));
        }
        try {
            shortestStay = Integer.parseInt(result.get(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            longestStay = Integer.parseInt(result.get(1));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            checkInEarly = Integer.parseInt(result.get(2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
